// This file is required by the index.html file and will
// be executed in the renderer process for that window.
// All of the Node.js APIs are available in this process.
const { ipcRenderer } = require('electron')
const { $ } = require('./component/helper')
const path = require('path')

let isSelect = true     // 表述当前按钮是否为选择文件状态
let selectFiles = []    // 记录选中的文件

$('select-music').addEventListener('click', () => {
  if (isSelect)
    ipcRenderer.send('select-music')
  else
    ipcRenderer.send('import-music', selectFiles)
})


const renderListHtml = (files) => {
  // ES6 的模板功能渲染选择文件
  let musicItemHtml = files.reduce((html, file) => {
    return html + `<li class="list-group-item">${path.basename(file)}</li>`
  }, '')
  $('fileList').innerHTML = `<ul class="list-group">${musicItemHtml}</ul>`
}

ipcRenderer.on('load-music', (event, files) => {
  if (Array.isArray(files)) {
    renderListHtml(files)
    selectFiles = files
    isSelect = false
    $('select-music').innerText = '导入'
  }
})

ipcRenderer.on('import-music-finish', () => {
  selectFiles = []
  isSelect = true
  $('fileList').innerHTML = ''
  $('select-music').innerText = '选择文件'
})